import {Component, EventEmitter, Input, OnInit, Output} from '@angular/core';
import {FormBuilder, FormControl, FormGroup} from '@angular/forms';
import {HttpService} from '../../service/http-service/http.service';
import {testURL} from '../../service/http-service/URL';
import {SelectItem} from 'primeng/api';
import {SearchFromItem, TableHeader} from './tableData';

@Component({
  selector: 'app-table',
  templateUrl: './table.component.html',
  styleUrls: ['./table.component.css']
})
export class TableComponent implements OnInit {
  @Input() config: SearchFromItem[]; // 搜索部分的数据
  @Input() columns: TableHeader[]; // 表头和对应字段
  @Input() values: any; // 表格数据
  @Input() key: any = 'id'; // 表格主键
  @Input() multiple: boolean = true; // 勾选框
  @Input() buttons: any;
  @Output() clickBut = new EventEmitter(); // 点击按钮返回父组件响应的数据
  totalNum: number; // 总条数
  pageSize: number = 10; // 每页多少条
  pageNum: number = 1; // 当前页码数
  startIndex: number = 0; // 每页开始的下标
  loading: boolean; // 是否显示正在加载的图标
  selected: any; // 已经选中的数据
  searchFrom: FormGroup; // 搜索表单
  ch: any;
  select: SelectItem[];

  constructor(private fb: FormBuilder, private httpService: HttpService) {
    this.ch = {
      firstDayOfWeek: 0,
      dayNames: ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'],
      dayNamesShort: ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'],
      dayNamesMin: ['日', '一', '二', '三', '四', '五', '六'],
      monthNames: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],
      monthNamesShort: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],
      today: '今天',
      clear: '清除'
    };
  }

  ngOnInit() {
    this.loading = true;
    this.searchFrom = this.formGroup();
  }

  /*初始化搜索表单*/
  formGroup() {
    const group = {};
    this.config.forEach(event => {
      group[event.name] = new FormControl(event.value || '');
    });
    return new FormGroup(group);
  }

  /*重置表单*/
  refresh() {
    this.searchFrom.reset();
  }

  /*搜索*/
  search() {
    this.config.forEach(event => {
      /*判断是不是time，想表单里的value值转换成时间戳，controls为表单属性*/
      if (event.type === 'time' && this.searchFrom.value[event.name]) {
        this.searchFrom.value[event.name] = Date.parse(this.searchFrom.controls[event.name].value);
      }
    });
    console.log(this.searchFrom.value);
  }

  createGroup() {
    const group = this.fb.group({});
    this.config.forEach(control => group.addControl(control.name, this.fb.control('')));
    return group;
  }

  loadCarsLazy(event) {
    this.loading = true;
    setTimeout(() => {
      this.loading = false;
    }, 1000);
    this.httpService.http('get', testURL.list).then(
      res => {
        console.log(res);
      }
    );
  }

  goToNewPage() {

  }

  /*点击按钮，返回点击的按钮属性和当前行的数据*/
  butClick(button, list) {
    this.clickBut.emit({
      button: button,
      list: list
    });
  }
}
